class_name ChannelCard
extends HBoxContainer

signal initialized
signal is_setup

const THUMBNAIL_SIZE := Vector2(50, 50)
const THUMBNAIL_INTERPOLATION_METHOD: int = Image.INTERPOLATE_LANCZOS

export(String, FILE) var default_thumbnail_path = "res://icon.png"

# URL of the channel on the LBRY blockchain
var _channel_url: String
# All the resolved data for this `_channel_url`
var _data: Dictionary = {}
var _is_setup: bool = false
var _default_thumbnail_img := Image.new()
var _initialized: bool = false
var _async_helper := AsyncHelper.new(self)
onready var _spinner_node: Spinner = find_node("Spinner")
onready var _channel_thumbnail_node: TextureRect = \
		find_node("ChannelThumbnail")
onready var _channel_title_node: Label = find_node("ChannelTitle")
onready var _channel_name_node: Label = find_node("ChannelName")


func init(channel_url: String) -> void:
	_channel_url = channel_url
	_initialized = true
	emit_signal("initialized")


func _ready() -> void:
	if not _initialized:
		yield(self, "initialized")
	
	var thumbnail := ImageTexture.new()
	_default_thumbnail_img = load(default_thumbnail_path).get_data()
	# Make sure the thumbnail enters the scene as the correct size
	_default_thumbnail_img.resize(int(THUMBNAIL_SIZE.x), int(THUMBNAIL_SIZE.y))
	thumbnail.create_from_image(_default_thumbnail_img)
	_channel_thumbnail_node.set_texture(thumbnail)
	
	_setup()


func get_channel_url() -> String:
	return _get_tooltip()


func get_channel_name() -> String:
	return _channel_name_node.get_text()


func get_channel_title() -> String:
	return _channel_title_node.get_text()


func is_setup() -> bool:
	return _is_setup


func _setup() -> void:
	if _channel_url == "":
		return
	
	var tracker: Dictionary = _async_helper.connect_wrapped(
			SDK.resolve([_channel_url]), "completed")
	yield(_async_helper.wait_until_finished([tracker]), "completed")
	var resolve_response: Dictionary = tracker["result"]
	if resolve_response.has("result"):
		_data = resolve_response["result"].get(
				resolve_response["result"].keys()[0])
	
	var resources: Array = yield(_get_resources(), "completed")
	var channel_name: String = resources[0]
	var channel_title: String = resources[1]
	var thumbnail_img: Image = resources[2]
	
	# Update _channel_url to the short URL if it was found
	if resources[0] != "":
		_channel_url = "lbry://" + resources[0]
	
	if channel_title == "":
		channel_title = channel_name.substr(1).rsplit("#", true, 1)[0]
	
	_channel_name_node.set_text(channel_name)
	_channel_title_node.set_text(channel_title)
	_set_channel_thumbnail(thumbnail_img)
	set_tooltip(_channel_url)
	_is_setup = true
	emit_signal("is_setup")


func _get_resources() -> Array:
	"""
	Returns:
		The channel name (String), channel title (String) and channel thumbnail
		(ImageTexture). If the channel name or title is not found, then an
		empty string. If the thumbnail could not be loaded or contained no
		data, then `null`
	"""
	var channel_name: String = ""
	var channel_title: String = ""
	var tracker: Dictionary
	
	channel_name = _data.get("short_url", "").trim_prefix("lbry://")
	channel_title = _data.get("value", {}).get("title", "")
	
	var channel_thumbnail_url: String = _data \
			.get("value", {}) \
			.get("thumbnail", {}) \
			.get("url", "")
	tracker = _async_helper.connect_wrapped(
			Requests.get_image(channel_thumbnail_url), "completed")
	yield(_async_helper.wait_until_finished([tracker]), "completed")
	var channel_thumbnail_img: Image = tracker["result"]
	return [channel_name, channel_title, channel_thumbnail_img]


func _set_channel_thumbnail(image: Image) -> void:
	var channel_thumbnail := ImageTexture.new()
	if image.is_empty():
		image = _default_thumbnail_img
	else:
		image.resize(int(THUMBNAIL_SIZE.x), int(THUMBNAIL_SIZE.y),
				THUMBNAIL_INTERPOLATION_METHOD)
	channel_thumbnail.create_from_image(image)
	_channel_thumbnail_node.set_texture(channel_thumbnail)
	_channel_thumbnail_node.show()
	_spinner_node.hide()
